<template>
  <div class="about">
    <div>

      <el-form :inline="true" :model="formInline" class="demo-form-inline">
        <el-form-item label="姓名">
          <el-input v-model="formInline.name" placeholder="审批人"></el-input>
        </el-form-item>
        <!--<el-form-item label="活动区域">
          <el-select v-model="formInline.region" placeholder="活动区域">
            <el-option label="区域一" value="shanghai"></el-option>
            <el-option label="区域二" value="beijing"></el-option>
          </el-select>
        </el-form-item>-->


        <el-form-item>
          <el-button type="primary" @click="onSubmit">查询</el-button>
<!--          <el-button type="success" @click="dialogFormVisible=true">新增</el-button>-->
          <el-button type="success" @click="toAdd">新增</el-button>
          <el-button type="warning" plain @click="delBatch">批量删除</el-button>
        </el-form-item>
      </el-form>
    </div>
    <el-table
            ref="multipleTable"
            :data="tableData"
            tooltip-effect="dark"
            style="width: 100%"
            @selection-change="handleSelectionChange">


      <el-table-column
              type="selection"
              width="55">
      </el-table-column>
      <el-table-column
              prop="id"
              label="id"
              width="120">
      </el-table-column>
      <el-table-column
              prop="name"
              label="姓名"
              width="120">
      </el-table-column>
      <el-table-column
              prop="address"
              label="地址"
              width="200">

      </el-table-column>
      <el-table-column
              prop="phone"
              label="电话"
              width="120">
      </el-table-column>
      <el-table-column

              label="头像"
              width="130">
            <template slot-scope="scope">
              <el-image style="height: 30px" :src="scope.row.userface"></el-image>
            </template>
      </el-table-column >
      <el-table-column

              label="是否禁用"
              width="130">
        <template slot-scope="scope">
          <el-switch
                  v-model="scope.row.enabled"
                  @change="changeStatus"
                  active-color="#13ce66"
                  inactive-color="#ff4949">
          </el-switch>
        </template>
      </el-table-column >

      <el-table-column
              label="操作"
              width="500">
        <template slot-scope="scope">
            <el-button type="primary" @click="edit(scope.row)">编辑</el-button>
            <el-button type="danger" @click="del(scope.row.id)">删除</el-button>
            <el-button type="success" @click="toRolePage(scope.row.id)">设置角色</el-button>
        </template>


      </el-table-column>
    </el-table>
    <div style="margin-top: 20px">

      <div class="block">
        <el-pagination
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="currentPage"
                :page-sizes="[3, 6, 9, 12]"
                :page-size="pageSize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="total">
        </el-pagination>
      </div>
    </div>



    <!-- Form 对话框-->

    <el-dialog title="用户信息" :visible.sync="dialogFormVisible">
      <el-form :model="user">
        <el-form-item label="姓名" :label-width="formLabelWidth">
          <el-input v-model="user.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="用户名" :label-width="formLabelWidth">
          <el-input v-model="user.username" autocomplete="off"></el-input>
        </el-form-item>
        <!--<el-form-item label="密码" :label-width="formLabelWidth">
          <el-input v-model="user.password" autocomplete="off"></el-input>
        </el-form-item>-->
        <div class="block">
          <span class="demonstration">生日</span>
          <el-date-picker
                  v-model="user.birthday"
                  type="date"
                  value-format="yyyy-MM-dd"
                  placeholder="选择日期">
          </el-date-picker>
        </div>


        <div class="block">
          <span class="demonstration">地址</span>
          <el-cascader
                  v-model="value"
                  :options="options"
                  @change="handleChange"></el-cascader>
        </div>

        <span>{{value}}</span><br>
        <span>图片上传</span>
        <el-upload

                class="avatar-uploader"
                action="http://localhost:9001/user/faceUpload"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload">
          <img v-if="imgUrl" :src="imgUrl" class="avatar">
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="add">提交</el-button>
      </div>
    </el-dialog>


    <!--设置角色的对话框-->
    <el-dialog title="收货地址" :visible.sync="dialogTableVisible">
      <el-button type="warning" @click="setRole">设置</el-button>
      <el-table ref="multipleTable" tooltip-effect="dark" :data="gridData" @selection-change="handleSelectionChange">
        <el-table-column
                type="selection"
                width="55">
        </el-table-column>
        <el-table-column property="id" label="序号" width="150"></el-table-column>
        <el-table-column property="nameZh" label="角色名称" width="200"></el-table-column>

      </el-table>
    </el-dialog>
  </div>
</template>
<script>
  export default {
    data() {
      return {
        imgUrl:'',
        value:[],//三级联动的时候,选中的数据
        options:[],
        gridData: [],//角色的列表数组
        dialogTableVisible: false,
        dialogFormVisible: false,
        user: {
          id:0,
          name: '',
          birthday: '',
          province: 0,
          city: 0,
          district: 0,
          userface:'',
          username: ''
        },
        formLabelWidth: '60px',
        formInline: {
          name: ''
        },
        tableData: [],
        multipleSelection: [],//选中的数据,存的是一行行的数据

        currentPage:1,
        pageSize: 3,
        total: 0,
        uid:0  //设置角色的时候,接收用户id
      }
    },

    methods: {
      changeStatus(newStatus){
        console.log(newStatus+"&&&&&&&&&")

      },

      setRole(){
        //发送ajax请求到后台参数是:uid,选中的数据
        this.axios.post("http://localhost:9001/user/setRole?uid="+this.uid,this.multipleSelection).then(resp=>{

            console.log(resp.data.code+"*************")
          if(resp.data.code=="200"){
            alert("success")
            this.dialogTableVisible=false;
          }
        })

      },

      //弹出设置角色的对话框
      toRolePage(uid){
        this.uid=uid;
        this.dialogTableVisible = true//显示对话框

        //查询角色列表
        this.axios.get("http://localhost:9001/role/list").then(resp=>{
            // console.log(resp.data.data.records+"============")
          //为了设置角色的时候,用户原来的角色回显,我们必须根据用户的id,查询该用户对应的角色
          //所有角色
          this.gridData=resp.data.data.records;

          this.axios.get("http://localhost:9001/role/findRolesByUid?uid="+uid).then(re=>{
            //对象 拥有角色
            this.multipleSelection=re.data.data;


            this.multipleSelection.forEach(row1 => {
              this.gridData.forEach(myrow=>{
                //当用户拥有的角色,和所有角色中的id一样的话,选中
                if (myrow.id==row1.id){
                  this.$refs.multipleTable.toggleRowSelection(myrow,true);
                  console.log(JSON.stringify(myrow))
                }
              })
            });

          })

        })
      },

      //编辑
      edit(row){

        //2.回显数据,三级联动的所有数据要查询出来
        //1.查询省市区的数据
        this.axios.get("http://localhost:9001/city/list").then(resp=>{
          //赋值操作
          //在赋值之前,进行一步处理,把控的children数组去掉
          this.options=this.delNull(resp.data);
        })
        this.value=[];
        this.axios.get("http://localhost:9001/user/getOne?id="+row.id).then(resp=>{
          this.user=resp.data.data;
          //三级联动回显
          this.value.push(resp.data.data.province,resp.data.data.city,resp.data.data.district)
          //图片回显
          this.imgUrl=resp.data.data.userface
        })

        //2.打开对话框
        this.dialogFormVisible=true
        //编辑的对话框展示出来,使用新增的对话框就可以了
      },

      delBatch(){
        var uids = this.multipleSelection.map(row => row.id).join(',');//从数组中拿到每个对象的id,用一个新的变量接收
        alert(uids)
        this.axios.get("http://localhost:9001/user/del?ids="+uids).then(resp=>{
          if(resp.data.code=="200"){
            alert("删除成功")
            this.initList();
          }else{
            alert("删除失败")
          }
        })
      },

      del(id){
        // var ids = new Array();
        // ids.push(id)
                //发送请求到后台,根据id删除
        this.axios.get("http://localhost:9001/user/del?ids="+id).then(resp=>{
          if(resp.data.code=="200"){
            alert("删除成功")
            this.initList();
          }else{
            alert("删除失败")
          }
        })
      },

      //图片上传成功之后,执行的方法
      handleAvatarSuccess(res, file) {
        this.imgUrl = URL.createObjectURL(file.raw);
        console.log(res);
        this.user.userface=res.data[0].fileUrl

      },
      //图片上传之前执行的方法
      beforeAvatarUpload(file) {
        const isJPG = file.type === 'image/jpeg';
        const isLt2M = file.size / 1024 / 1024 < 2;

        if (!isJPG) {
          this.$message.error('上传头像图片只能是 JPG 格式!');
        }
        if (!isLt2M) {
          this.$message.error('上传头像图片大小不能超过 2MB!');
        }
        return isJPG && isLt2M;
      },

      handleChange(value) {
        console.log(value);
        this.user.province=this.value[0];
        this.user.city=this.value[1];
        this.user.district=this.value[2];
      },
      add(){
        //1.发送请求保存数据到后台
        this.axios.post("http://localhost:9001/user/add",this.user).then(resp=>{
          if(resp.data.code=='200'){
            alert(resp.data.message)
            this.initList()
          }else{
            alert(resp.data.message)
          }
        })
        //2.关闭该对话框
        this.dialogFormVisible=false;
      },
      toAdd(){
        //1.查询省市区的数据
        this.axios.get("http://localhost:9001/city/list").then(resp=>{
          //赋值操作

          //在赋值之前,进行一步处理,把控的children数组去掉
          this.options=this.delNull(resp.data);
        })

        //2.打开对话框
        this.dialogFormVisible=true
      },
      delNull(data){
        // 把控的children数组去掉的方法
        if(data!=null){
          for (var i=0;i<data.length;i++ ){
            if(data[i].children&&data[i].children.length<1){
              data[i].children=undefined;
            }else{
              this.delNull(data[i].children)
            }
          }
        }
        return data;
      },
      onSubmit() {
        console.log('submit!');

        this.initList();
      },
      handleSizeChange(val) {
        console.log(`每页 ${val} 条`);
        this.pageSize=val;
        this.initList()
      },
      handleCurrentChange(val) {
        console.log(`当前页: ${val}`);
        this.currentPage=val;
        this.initList();
      },
      toggleSelection(rows) {
        if (rows) {
          rows.forEach(row => {
            this.$refs.multipleTable.toggleRowSelection(row);
          });
        } else {
          this.$refs.multipleTable.clearSelection();
        }
      },
      handleSelectionChange(val) {
        //这一步,就是存储了所有对象的集合
        this.multipleSelection = val;

      },
      initList(){
        //发送一个请求到后台,查询列表
        this.axios.get("http://localhost:9001/user/list",
                {params:{
                    name:this.formInline.name,
                    pageNum:this.currentPage,
                    pageSize:this.pageSize


                }}).then((resp)=>{
          console.log(resp.data)
          this.tableData=resp.data.data.records;
          this.total=resp.data.data.total
        })
      }
    },
    created() {
      this.initList();
    }
  }
</script>
<style>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>
